<!--
*@Author: QWP
*@Description: 用车申请编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs"
    :confirmLoading="loading"
    :destroyOnClose="true"
    @submit="submit"
    @close="dialogClose">
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white"
        style="overflow: auto">
        <u-busi-card title="派车信息"
          :bordered="false">
          <u-form :elements="formEls"
            :model="form"
            :gutter="0"
            :loading="loading"
            ref="formRef">
          </u-form>
        </u-busi-card>
        <u-busi-card title="归队图片">
          <u-upload-img v-model:value="carImgs"
            :fileParams="{biztype: '8', bucket: 'VEHICLE_BIZ_TYPE_DISPATCHDETAIL'}"
            accept=".jpg, .png, .jpeg, .gif"/>
        </u-busi-card>
      </a-layout-content>
    </a-layout>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useLoginStore,  useBaseStore } from '@/store'
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { alertC, messageC, nullC, isValue } from '@/util/common';
import { cloneDeep } from 'lodash'
import dayjs from 'dayjs';
import * as backApi from '@/service/administration/sendback'

const props = withDefaults(
  defineProps<{ current?: object }>(),
  {
    current: {}
  }
)

const attrs = useAttrs()
const emits = defineEmits(['success'])
const { userInfo } = storeToRefs(useLoginStore())

// 归队图片
const carImgs = ref([])

// 表单信息
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '120px',
  colon: false
}
const formEls: Array<_IFormEl> = [
  { label: '驾驶员', key: 'drivername', col: { span: 12,}, element: 'input', 
    formItemProps: formItemProps,
    componentProps: { disabled: true } 
  },
  { label: '车牌号', key: 'platenumber', col: { span: 12 }, element: 'input', 
    formItemProps: formItemProps,
    componentProps: { disabled: true } 
  },
  { label: '出发地点', key: 'departure', col: { span: 12 }, element: 'selAddress', 
    formItemProps: formItemProps ,  
    componentProps: { disabled: true } 
  },
  { label: '前往地点', key: 'destination', col: { span: 12 }, element: 'selAddress', 
    formItemProps: formItemProps, 
    componentProps: { disabled: true }  
  },
  { label: '出发里程', key: 'startkilometer', col: { span: 12 }, element: 'number', 
    formItemProps: { ...formItemProps, required: true,
      rules: [
        { trigger: 'blur', 
          validator: async(_rule: Rule, value: string) => {
            if (value > form.value.endkilometer) {
              return Promise.reject('出发里程不能大于归队里程');
            }
            return Promise.resolve();
          }
        },
      ]
    },  
    componentProps: {
      controls: false, precision: 0, addonAfter: 'KM',
      onChange:() => {
        if(form.value.endkilometer) {
          formRef.value.form.validateFields(['endkilometer'])
        }
      }
    }
  },
  { label: '归队里程', key: 'endkilometer', col: { span: 12 }, element: 'number', 
    formItemProps: { ...formItemProps, required: true, 
      rules: [
        { trigger: 'blur',
          validator: async(_rule: Rule, value: string) => {
            if (value < form.value.startkilometer) {
              return Promise.reject('归队里程不能小于出发里程');
            }
            return Promise.resolve();
          }
        },
      ]
    } , 
    componentProps: {
      controls: false, precision: 0, addonAfter: 'KM',
      onChange:() => {
        if(form.value.startkilometer) {
          formRef.value.form.validateFields(['startkilometer'])
        }
      }
    } 
  },
  { label: '备注', key: 'remark', col: { span: 24 }, element: 'textarea', 
    formItemProps: { ...formItemProps, } ,  
    componentProps: {
      maxlength: 200, showCount: true
    }
  },
]

// 保存
const submit = async (type?: string) => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    messageC("请先将必填项填写完毕！")
    return
  }

  const url = form.value.keyid ? "update" : "add";

  let copyform = cloneDeep(form.value);
  copyform.appendixSaveVOList = carImgs.value
  
  loading.value = true;
  try {
    const data = await backApi.update(copyform)
    if (data.code == 0) {
      messageC(data.msg, "success")
      emits("success");
      dialogClose()
    } else {
      messageC(data.msg, "warning");
    }
  } catch (error) {}
  loading.value = false;
}

// 回显
const getHxData = async () => {
  loading.value = true;
  try {
    const data = await backApi.query(form.value.keyid);
    if(data.code == 0) {
      form.value = data.data
      form.value.startkilometer = data.data['startkilometer'] || ''
      carImgs.value = data.data['appendix'] || []
    }
  } catch (error) {}
  loading.value = false;
}

// 弹窗关闭
const dialogClose = () => {
  if(formRef.value) {
    formRef.value.form.resetFields();
  }
  form.value = {}
  carImgs.value = []
}

watch(() => attrs.open, (nval, oval) => {
  if (nval == true) {
    let keyid = (props.current || {})['keyid'] || ''
    if (keyid != "") {
      form.value.keyid = keyid;
      getHxData();
    }
  }
})
</script>

<style lang='scss' >
</style>